import { Component, Input, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Consts } from 'src/app/consts/consts';
import { RoleQueryParam } from 'src/app/models/param/role-query.param';
import { RoleUserQueryParam } from 'src/app/models/param/role-user-query.param';
import { MenuDto } from 'src/app/models/sys/menu.dto';
import { RoleDto } from 'src/app/models/sys/role.dto';
import { UserDto } from 'src/app/models/sys/user.dto';
import { ApiService } from 'src/app/services/api.service';

@Component({
  selector: 'app-client-role',
  templateUrl: './client-role.component.html',
  styleUrls: ['./client-role.component.less']
})
export class ClientRoleComponent implements OnInit {
  @Input() clientId!: BehaviorSubject<string>;
  clientIdVal?: string;

  roles: RoleDto[] = [];
  roleClicked = false;

  // Role Users页面查询用的参数
  userParam = new BehaviorSubject<RoleUserQueryParam>(new RoleUserQueryParam());
  // Role Permissions页面所需的roleId
  roleId = new BehaviorSubject<number>(0);

  // 角色对应权限权限。
  detailHeader?: string = "aaa";
  menus: MenuDto[] = [];
  // 角色分配给了哪些用户
  users = new BehaviorSubject<UserDto[]>([]);
  

  constructor(private _api: ApiService) {}

  ngOnInit(): void {
    this.clientId.subscribe((value) => {
      this.clientIdVal = value;
      this.onSearchRole();
    });

  }

  onSearchRole() {
    const param = new RoleQueryParam();
    param.clientId = this.clientIdVal;
    this._api.getRoleList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.roles = resp.data;
        if (this.roles.length > 0) {
          this.detailHeader = this.roles[0].roleName;
        }
      }
    });
  }

  onRoleClick(role: RoleDto) {
    console.log(`role clicked ${role}`);
    this.roleClicked = true;
    const param = new RoleUserQueryParam();
    param.clientId = this.clientIdVal;
    param.roleKey = role.roleKey;

    this.userParam.next(param);
    this.roleId.next(role.roleId);

    this.detailHeader = role.roleName;
  }
}
